package com.netease.nie.service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.netease.nie.base.exceptions.BusinessException;
import com.netease.nie.constants.BusinessConstants;
import com.netease.nie.dao.ExchangeCodeDao;
import com.netease.nie.model.ExchangeCode;

@Service
public class ExchangeCodeServiceImpl implements ExchangeCodeService {

	@Resource
	private ExchangeCodeDao exchangeCodeDao;

	public ExchangeCode queryExchangeCodeById(int id) {
		ExchangeCode exchangeCode = exchangeCodeDao.queryExchangeCodeById(id);
		if (exchangeCode == null)
			throw new BusinessException(
					BusinessConstants.EXCHANGE_CODE_NOT_EXISTS.getCode(), "兑换码不存在");
		return exchangeCode;
	}
	
	public Map<Integer, ExchangeCode> queryExchangeCodeByIds(List<Integer> ids) {
		if (ids != null && !ids.isEmpty()) {
			List<ExchangeCode> exchangeCodeList = exchangeCodeDao.queryExchangeCodeByIds(ids);
			if (exchangeCodeList == null)
				throw new BusinessException(
						BusinessConstants.EXCHANGE_CODE_NOT_EXISTS.getCode(), "兑换码不存在");
			
			if (exchangeCodeList == null || exchangeCodeList.isEmpty())
				return Collections.emptyMap();
			
			Map<Integer, ExchangeCode> exchangeCodeMap = new HashMap<>();
			
			int size = exchangeCodeList.size();
			int exchangeCodeId;
			ExchangeCode exchangeCode = null;
			
			for (int i = 0; i < size; ++i) {
				exchangeCode = exchangeCodeList.get(i);
				exchangeCodeId = exchangeCode.getId();
				exchangeCodeMap.put(exchangeCodeId, exchangeCode);
			}
			
			return exchangeCodeMap;
		}
		return Collections.emptyMap();
	}
	
	public int registerExchangeCodeOwner(int exchangeCodeId, long userId, long exchangeTime, int customGoodsCode, int customGoodsId) {
		try {
			return exchangeCodeDao.registerExchangeCodeOwner(exchangeCodeId, userId, exchangeTime, customGoodsCode, customGoodsId);
		} catch (Exception e) {
			return 0;
		}
	}
	
}
